<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="./jquery-1.11.1.min.js"></script>
    <style>
      .box {
        width: 280px;
        border: 1px dashed gainsboro;
        margin-bottom: 10px;
        padding: 10px 30px;
      }
      .bottom-box {
        height: 100px;
      }
      .btn-box {
        margin: 5px auto;
        width: 100px;
      }
      table {
        display: none;
        width: 300px;
      }
    </style>
  </head>
  <body>
    <div class="box">
      <div>网站名(key):<input id="putname" type="text" /></div>
      <div>网址(value):<input id="putvalue" type="text" /></div>
      <div class="btn-box"><button id="add">新增记录</button></div>
      <div class="bottom-box">
        <div>输入网站名：<input id="searchvalue" type="text" /></div>
        <div class="btn-box"><button id="search">查找网站</button></div>
        <div id="search-result"></div>
      </div>
    </div>
    <div id="add-result"></div>
    <table border="1">
      <tr>
        <td>key</td>
        <td>value</td>
      </tr>
    </table>
  </body>
  <script>
    var putName = document.getElementById("putname");
    var putValue = document.getElementById("putvalue");
    var searchValue = document.getElementById("searchvalue");
    var addResult = document.getElementById("add-result");
    var searchResult = document.getElementById("search-result");
    // if (localStorage.length > 0) {
    //     localStorage.setItem(putName.value, putValue.value);
    //     alert("添加成功");
    //     location.reload();
    //   } else {
    //     $("#add-result").html("没有数据...");
    //   }
    document.getElementById("add").onclick = function () {
        localStorage.setItem(putName.value, putValue.value);
        alert("添加成功");
        location.reload();
    };
    addResult.style.display = "none";
    $("table").css("display", "block");
    for (var i = 0; i < localStorage.length; i++) {
      $("table").append(
        `<tr><td>${localStorage.key(i)}</td><td>${localStorage.getItem(
          localStorage.key(i)
        )}</td> </tr>`
      );
    }
    document.getElementById("search").onclick = function () {
      for (key in localStorage) {
        return (searchResult.innerHTML = `${searchValue.value}
            的网址是:${localStorage.getItem(searchValue.value)}`);
      }
    };
  </script>
</html>
